package com.dianpingmedia.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.dianpingmedia.LogAspect;
import com.dianpingmedia.simulate.model.*;
import it.sauronsoftware.jave.Encoder;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class SmlUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(LogAspect.class.getSimpleName());

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    public static boolean isSupport(String url) {
        String ext = getFormat(url);
        return "mp4".equals(ext) || "MP4".equals(ext) || "JPG".equals(ext) || "PNG".equals(ext) || "JPEG".equals(ext) || "jpg".equals(ext) || "png".equals(ext) || "jpeg".equals(ext);
    }

    private static String getFormat(String url) {
        return url.substring(url.lastIndexOf(".") + 1);
    }

    private static String getName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public static Integer getMaterialType(String url) {
        String ext = getFormat(url);
        if ("mp4".equals(ext) || "MP4".equals(ext)) {
            return 2;
        } else {
            return 1;
        }
    }

    public static String convert(Long time) {
        return SmlUtils.format.format(time);
    }


    public static Object[] returnImgWH(String imgUrl, String path) {
        boolean b = false;
        Object[] a = new Object[4];
        String filePath = path + File.separator + getName(imgUrl);
        b = download(imgUrl, filePath);
        LOGGER.info(imgUrl + " DOWNLOAD STATUS:" + b);
        if (b) {//图片存在
            java.io.File file = new java.io.File(filePath);
            BufferedImage bi = null;
            boolean imgwrong = false;
            try {
                //读取图片
                bi = javax.imageio.ImageIO.read(file);
                try {
                    //判断文件图片是否能正常显示,有些图片编码不正确
                    int i = bi.getType();
                    imgwrong = true;
                } catch (Exception e) {
                    imgwrong = false;
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (imgwrong) {
                try {
                    a[3] = 15;
                    a[2] = DigestUtils.md5Hex(new FileInputStream(filePath));
                    a[1] = bi.getHeight(); //获得 高度
                    a[0] = bi.getWidth(); //获得 宽度
                    return a;
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    file.delete();
                }
            } else {
                a = null;
            }
        } else {//图片不存在
            a = null;
        }
        return null;

    }

    public static Object[] returnWH(String url, String storage_directory) {
        File directory = new File(storage_directory);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        if (getMaterialType(url) == 1) {
            return returnImgWH(url, storage_directory);
        } else {
            return returnVideoWH(url, storage_directory);
        }
    }

    private static Object[] returnVideoWH(String videoUrl, String path) {
        boolean b = false;
        Object[] a = new Object[4];
        String filePath = path + File.separator + getName(videoUrl);
        b = download(videoUrl, filePath);
        LOGGER.info(videoUrl + " DOWNLOAD STATUS:" + b);
        if (b) {
            File file = new File(filePath);
            Encoder encoder = new Encoder();
            try {
                it.sauronsoftware.jave.MultimediaInfo m = encoder.getInfo(file);
                a[3] = m.getDuration() / 1000;
                a[2] = DigestUtils.md5Hex(new FileInputStream(filePath));
                a[1] = m.getVideo().getSize().getHeight();
                a[0] = m.getVideo().getSize().getWidth();
                return a;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                file.delete();
            }
        }
        return null;
    }

    private static boolean download(String videoUrl, String filePath) {
        boolean b;
        try {
            URL url = new URL(videoUrl);
            BufferedInputStream bis = new BufferedInputStream(url.openStream());
            byte[] bytes = new byte[100];
            OutputStream bos = new FileOutputStream(new File(filePath));
            int len;
            while ((len = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, len);
            }
            bis.close();
            bos.flush();
            bos.close();
            b = true;
        } catch (Exception e) {
            b = false;
        }
        return b;
    }


    public static Map<String, List<IFlyAdunitEntity>> iFlySyncAdunitReturn(List<IFlySyncAdunitEntity.Request.Adunit> adunits) {

        return new HashMap<String, List<IFlyAdunitEntity>>() {
            {
                put("100", new ArrayList<IFlyAdunitEntity>() {
                    {
                        for (IFlySyncAdunitEntity.Request.Adunit adunit : adunits) {
                            Integer width = adunit.getWidth();
                            Integer height = adunit.getHeight();
                            if (width != null && width != 0 && height != null && height != 0 && !StringUtils.isEmpty(adunit.getAdunit_name())) {
                                add(new IFlyAdunitEntity(width, height, MiscUtil.MD5(adunit.getAdunit_name())));
                            }
                        }
                    }
                });
            }
        };
    }


    /**
     * 讯飞媒体位同步模拟返回
     *
     * @param medias
     * @return
     */
    public static Map<String, Map<String, String>> iFlySyncMediaReturn(List<IFlySyncMediaEntity.Request.Media> medias) {
        return new HashMap<String, Map<String, String>>() {
            {
                HashMap<String, String> value = new HashMap<String, String>() {{
                    for (IFlySyncMediaEntity.Request.Media media : medias) {
                        String screen_id = media.getScreen_id();
                        if (!StringUtils.isEmpty(screen_id)) {
                            String screenIdMd5 = MiscUtil.MD5(screen_id);
                            if (!StringUtils.isEmpty(screenIdMd5)) {
                                put(screen_id, screenIdMd5.substring(0, 8));
                            }
                        }
                    }
                }};
                put("100", value);
            }
        };
    }


    public static Map<String, List<IFlyRelationEntity>> iFlySyncRelationReturn(List<IFlySyncRelationEntity.Request.Rel> rels) {
        return new HashMap<String, List<IFlyRelationEntity>>() {
            {
                put("100", new ArrayList<IFlyRelationEntity>() {{
                    for (IFlySyncRelationEntity.Request.Rel rel : rels) {
                        if (!StringUtils.isEmpty(rel.getMedia_id()) && !StringUtils.isEmpty(rel.getAdunit_id())) {
                            add(new IFlyRelationEntity(rel.getMedia_id(), rel.getAdunit_id()));
                        }
                    }
                }});
            }
        };
    }


}
